/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.mybatisplus.handler;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.moon.framework.autoconfigure.secure.AuthUtils;
import org.moon.framework.autoconfigure.secure.domain.AuthInfo;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * 审计字段自动填充
 * @author moon
 */
@AutoConfigureAfter({MybatisPlusAutoConfiguration.class})
@Configuration
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

	private final static String CREATE_BY = "createBy";
	private final static String UPDATE_BY = "updateBy";
	private final static String CREATE_DEPT = "createDept";
	private final static String CREATE_TIME = "createTime";
	private final static String UPDATE_TIME = "updateTime";

	@Override
	public void insertFill(MetaObject metaObject) {
		Object createTime = getFieldValByName(CREATE_TIME, metaObject);
		if(createTime==null){
			setFieldValByName(CREATE_TIME, new Date(), metaObject);
		}
		Object createBy = getFieldValByName(CREATE_BY, metaObject);
		if(createBy==null){
			setFieldValByName(CREATE_BY, AuthUtils.getAuthInfo().getId(), metaObject);
		}
		Object createDept = getFieldValByName(CREATE_DEPT, metaObject);
		if(createDept==null){
			setFieldValByName(CREATE_DEPT, AuthUtils.getAuthInfo().getDeptId(), metaObject);
		}
		updateFill(metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
		if(updateTime==null){
			setFieldValByName(UPDATE_TIME, new Date(), metaObject);
		}
		Object updateBy = getFieldValByName(UPDATE_BY, metaObject);
		if(updateBy==null){
			setFieldValByName(UPDATE_BY, AuthUtils.getAuthInfo().getId(), metaObject);
		}
	}
}